﻿using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Wasion.HHU.Data.Models;
using Wasion.HHU.Data.Repositories;
using SQLite.Net;
using System;
using System.Linq.Expressions;

namespace Wasion.HHU.Data.Repositories
{
    public class SchemaDbRepository : BaseDbRepository
    {
        public SchemaDbRepository() : base()
        {

        }
        public SchemaDbRepository(SQLiteConnection connection)
            : base(connection)
        {
        }

        public Task<List<Schema>> GetAllList()
        {
            List<Schema> Schemas;

            lock (databaseLock)
            {
                Schemas = DbConnection.Table<Schema>().
                    OrderBy(x => x.SchName).
                    ToList();
            }
            return Task.FromResult(Schemas);
        }

        public Task<List<Schema>> GetList(Expression<Func<Schema, bool>> filter)
        {
            List<Schema> Schemas;

            lock (databaseLock)
            {
                Schemas = DbConnection.Table<Schema>().
                    OrderByDescending(x => x.SchName).
                    Where(filter).
                    ToList();
            }
            return Task.FromResult(Schemas);
        }

        public void Insert(Schema schema)
        {
            lock (databaseLock)
            {
                DbConnection.CreateTable<Schema>();
                DbConnection.Insert(schema);
            }
        }

        public void Update(Schema schema)
        {
            lock (databaseLock)
            {
                DbConnection.Update(schema);
            }
        }

        public Schema Find(object primaryKey)
        {
            Schema schema;

            lock (databaseLock)
            {
                schema = DbConnection.Find<Schema>(primaryKey);
            }
            return schema;
        }

        public void Delete(object primaryKey)
        {
            lock (databaseLock)
            {
                DbConnection.Delete<Schema>(primaryKey);
            }
        }

        public Task<List<SchemaItem>> GetAllSchemaItemList()
        {
            List<SchemaItem> schemaItems;

            lock (databaseLock)
            {
                schemaItems = DbConnection.Table<SchemaItem>().ToList();
            }
            return Task.FromResult(schemaItems);
        }
    }
}
